/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.envconfig;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.envconfig.model.EnvConfig;
import org.kohsuke.stapler.Stapler;

/**
 *
 * @author Pete
 */
public class GuiceServletConfig extends GuiceServletContextListener {
    private Injector injector;

    public GuiceServletConfig() {
        injector = Guice.createInjector(new ServletModule() {

            @Override
            protected void configureServlets() {
                Map<String, String> staplerParams = new HashMap<String, String>();
                staplerParams.put("default-encodings", "text/html=UTF-8");

                serve("/*").with(Stapler.class, staplerParams);
            }
        }, new EnvConfigModule());
    }

    @Override
    protected Injector getInjector() {
        return injector;
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // load up guice in standard manner
        super.contextInitialized(servletContextEvent);

        ServletContext servletContext = servletContextEvent.getServletContext();

        // Create the EnvConfig instance from this injector
        EnvConfig envConfig = injector.getInstance(EnvConfig.class);
        
        // Associate this root object with the Stapler servlet by setting this attribute
        servletContext.setAttribute("app", envConfig);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        super.contextDestroyed(servletContextEvent);
    }
}
